package com.admin.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.admin.bean.ConsumeOrderBean;
import com.admin.service.ConsumeOrderService;
import com.admin.service.SpService;
import com.admin.util.BaseUtil;
import com.admin.util.PageBean;

@Controller
@RequestMapping("/order")
public class ConsumeOrderAction {

	private static final Logger log = Logger.getLogger(ConsumeOrderAction.class);
	
	@Autowired private ConsumeOrderService consumeOrderService;
	@Autowired private SpService spService;
	
	@RequestMapping("/insert")
	public ModelAndView insert(HttpServletRequest request,HttpServletResponse response) throws IOException{
		log.info("=============开始生成消费记录===============");
		String telPhone = request.getParameter("telPhone");
		String port = request.getParameter("port");
		String command = request.getParameter("command");
		int consume = BaseUtil.stringToInt(request.getParameter("consume"));
		int count = spService.findSpByPortAndCommand(port, command);
		log.info("telPhone="+telPhone);
		log.info("port="+port);
		log.info("command="+command);
		log.info("consume="+consume);
		if(count==0){
			log.info("不是浏览器系统的消费记录！");
			return null;
		}
		boolean flag = consumeOrderService.insertOrder(telPhone, port, command, consume);
		String result = flag?"记录成功":"记录失败";
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		response.getWriter().print(result);
		log.info(result);
		log.info("==============消费记录结束================");
		return null;
	}
	
	@RequestMapping("/list")
	public String search(HttpServletRequest request){
		StringBuffer url = new StringBuffer();
		int status = BaseUtil.stringToInt(request.getParameter("status"),0);
		url.append("?status="+status);
		request.setAttribute("status", status);
		String telPhone = request.getParameter("telPhone");
		if(StringUtils.isNotEmpty(telPhone)){
			url.append("&telPhone="+telPhone);
			request.setAttribute("telPhone", telPhone);
		}
		int totalCount = consumeOrderService.findCount(telPhone, status);
		int currentPage = BaseUtil.stringToInt(request.getParameter("currentPage"),1);
		PageBean<ConsumeOrderBean> pageBean = new PageBean<ConsumeOrderBean>(totalCount,currentPage);
		pageBean.setUrl(url.toString());
		List<ConsumeOrderBean> orderList = consumeOrderService.findByCondition(telPhone, status, pageBean.getStart(), pageBean.getPageSize());
		pageBean.setResult(orderList);
		request.setAttribute("pageBean", pageBean);
		return "orderList";
	}
}
